<?php

namespace Yolo\Components\Cache;

use Hyperf\Context\ApplicationContext;
use Hyperf\Redis\RedisFactory;
use RedisException;
use Yolo\Di\Annotations\Singleton;

/**
 * Class RedisCache.
 */
#[Singleton]
class RedisCache implements CacheInterface
{

    private function getRedis()
    {
        return ApplicationContext::getContainer()->get(RedisFactory::class)->get('default');
    }

    /**
     * Get a value from the cache.
     * @param string $key
     * @return mixed
     * @throws RedisException
     */
    public function get(string $key): mixed
    {
        return $this->getRedis()->get($key);
    }

    /**
     * Set a value in the cache.
     * @param string $key
     * @param mixed $value
     * @param int $expireIn
     * @return void
     * @throws RedisException
     */
    public function set(string $key, mixed $value, int $expireIn = 3600): void
    {
        $redis = $this->getRedis();
        $redis->set($key, $value);
        $redis->expire($key, $expireIn);
    }

    /**
     * Delete a value from the cache.
     * @param string $key
     * @return int|bool
     * @throws RedisException
     */
    public function delete(string $key): int|false
    {
        return $this->getRedis()->del($key);
    }

    /**
     * Clear the cache.
     * @return void
     * @throws RedisException
     */
    public function clear(): void
    {
        $this->getRedis()->flushDB(true);
    }

    /**
     * Check if a key exists in the cache.
     * @param string $key
     * @return bool
     * @throws RedisException
     */
    public function exists(string $key): bool
    {
        return $this->getRedis()->exists($key);
    }
}
